stock = {

	ajax : false,
	type : false,
	hidden_form : false,

	list : {

		init : function()
		{
			stock.list.show_action();
			stock.list.bind_links();
			stock.list.search.init();
		},

		show_action : function()
		{
			$('.list-content .each')
			.bind('mouseenter', function(){
				$this = $(this);
				$this.children('.action').unbind('mouseenter').bind('mouseenter', function(){
					$this.unbind('click');
					$(this).bind('click', function(){
						tool.customAlert({'obj':'撤销后不能恢复，确认撤销？','confirm':true}, 'text', function(){
							stock.list.delete_stock($this);
						});
					}).css('background','#ccc');
				});
				$this.children('.action').removeClass('hide');
				$this.css('background','#eee')
			})
			.bind('mouseleave', function(){
				$this = $(this);
				$this.children('.action').unbind('mouseleave').bind('mouseleave', function(){
					tool.bind_link($this, site.url + 'stock/detail/' + $this.attr('stock-id'));
					$(this).unbind('click').css('background','none');
				});
				$this.children('.action').addClass('hide');
				$this.css('background','none')
			});
		},

		bind_links : function()
		{
			var $each_stock = $('#stock-list .list-content .each');
			$each_stock.each(function(){
				tool.bind_link($(this), site.url + 'stock/detail/' + $(this).attr('stock-id'));
			});
		},

		//撤销库存
		delete_stock : function($obj)
		{
			var url = site.url + 'stock/delete/';
			var json = '{"stock_id" : ' + $obj.attr('stock-id') + '}';
			data = tool.toJson(json);
			tool.customAlert({'obj':'提交中...请等候...','auto_close':true});
			style.loading('start');
			$.post(url, data, function(j){
				j = tool.toJson(j);
				tool.customAlert({'obj':j.d});
				style.loading('end');
				if ('DONE' == j.r)
				{
					$obj.addClass('deleted');
					$obj.find('.del').remove();
				}
			});
		},

		search : {

			init : function()
			{
				search = stock.list.search;
				search.select_stock_type();
				search.select_bound_type_flg();
			},

			select_stock_type : function()
			{
				$('select[name="stock_type"]').bind('change', function(){
					$this = $(this);
					stock_type = $this.val();
					url = site.url + 'ajax/get_bound_types/'+stock_type;
					$.post(url, function(json){
						console.log(json);
						bound_types = json.d;
						if (bound_types.length == 0)
						{
							$('select[name="bound_type_flg"]').find('.added-option').remove();
							$('select[name="bound_type_id"]').find('.added-option').remove();
						}
						else
						{
							search.add_options(bound_types, $('select[name="bound_type_flg"]'));
						}
					}, 'json');
				});
			},

			select_bound_type_flg : function()
			{
				$('select[name="bound_type_flg"]').bind('change', function(){
					$this = $(this);
					bound_type_flg = $this.val();
					stock_type = $('select[name="stock_type"]').val();
					url = site.url + 'ajax/get_bound_types/'+stock_type+'/'+bound_type_flg;
					$.post(url, function(json){
						console.log(json);
						bound_type_ids = json.d;
						if (bound_type_ids.length == 0)
						{
							$('select[name="bound_type_id"]').find('.added-option').remove();
						}
						else
						{
							search.add_options(bound_type_ids, $('select[name="bound_type_id"]'), 'name');
						}
					}, 'json');
				});
			},

			add_options : function(list, $select, name)
			{
				var options = '';
				for (var key in list)
				{
					if (undefined == name)
					{
						options += '<option class="added-option" value="'+key+'">'+list[key]+'</option>';
					}
					else
					{
						console.log(list);
						options += '<option class="added-option" value="'+key+'">'+list[key][name]+'</option>';
					}
				}
				$select.find('.added-option').remove();
				$select.append($(options));
			}

		}

	},

	detail : {
		init : function(){
			stock.detail.count_sub_goods_value();
		},

		count_sub_goods_value : function()
		{
			var $each_main = $('.each');
			$each_main.each(function()
			{
				var $sub_goods_value = $(this).find('.cost span');
				var sub_goods_value = 0;
				$(this).find('.each-sub').each(function(){
					sub_goods_value += parseInt($(this).children('.price').text()) * parseInt($(this).children('.quantity').text());
				});
				$sub_goods_value.text(sub_goods_value + '￥');
			});
		},
	},

	init : function()
	{
		$('.s-step').eq(0).css({'display':'block','margin-left':-790})
		.animate({'margin-left':0}, 500, function(){
			//绑定jDatepicker
			$('.jDatepicker').jDatepicker();
		});
		this.hidden_form = $('form[name="ready_submit"]');
		this.clear_col($('.stock-detail'), this.type);
		//添加搜索货物的方法
		$('input[name=s]').keyup(function(){
			$this = $(this);
			search_goods.search($this.val(), function(){
				//@ search_goods.item:Json 返回的搜索结果
				stock.show_result();
			});
		});
	},

	clear_col : function($obj, type){
		if ('N' == type)
		{
			$obj.find('.goods-supplier').remove();
			$obj.find('.goods-price').remove();
			$obj.find('.goods-transfer').remove();
		}
		else if ('S_P' == type)
		{
			$obj.find('.goods-transfer').remove();
			//Do nothing
		}
		else if ('S' == type)
		{
			$obj.find('.goods-price').remove();
			$obj.find('.goods-transfer').remove();
		}
		else if ('transfer' == type)
		{
			$obj.find('.goods-supplier').remove();
			$obj.find('.goods-price').remove();
			$obj.find('.store').remove();
		}
		else
		{
			$obj.remove();
			tool.customAlert({obj:'初始化出错，请返回重试:('});
			return false;
		}
		return true;
	},

	step : function($obj)
	{
		$cur_step = $obj.parents('.s-step');
		if (!this.step_process($('.s-step').index($cur_step) + 1))
		{
			return false;
		}
		to_step = $obj.attr('to-step');
		$next_step = $('.s-step').eq(to_step-1);
		$cur_step.animate({'margin-left':-790}, 500, function(){
			$(this).hide();
			$next_step.css({'display':'block','margin-left':-790})
			.animate({'margin-left':0}, 500);
		});
	},

	step_process : function(step)
	{
		$obj = $('.s-step').eq(step - 1);
		error = '';
		if (1 == step)
		{
			date = $obj.find('input[name="stock_date"]').val();
			date = date.split('-');
			if (date.length == 3 && 4 == date[0].length && (1 == date[1].length || 2 == date[1].length) && (1 == date[2].length || 2 == date[2].length))
			{
				this.hidden_form.find('input[name="stock_date"]').val(date[0] + '-' + date[1] + '-' + date[2]);
			}
			else
			{
				error += '日期格式不正确;';
			}
			desc = $obj.find('textarea').val();
			if ('' != desc.replace(/^\s+|\s+$/g,""))
			{
				this.hidden_form.find('input[name="description"]').val(desc);
			}
			else
			{
				error += '备注不能为空;';
			}
			bound_type_id = $obj.find('select[name="bound_type_id"] option:selected').val();
			if (undefined != bound_type_id && '' != bound_type_id.replace(/^\s+|\s+$/g,""))
			{
				this.hidden_form.find('input[name="bound_type_id"]').val(bound_type_id);
			}
			else
			{
				error += '请选择一个类型;';
			}
			if ('' != error)
			{
				tool.customAlert({obj:error});
				return false;
			}
		}
		return true;
	},

	show_result : function()
	{
		var data = search_goods.item;
		var html = '<div class="each">';
		html +=	'<div class="image"><img src="" /><div class="number"></div></div>';
		html +=	'<div class="colors"><!--<a sub_goods_id="" class="color"></a>--></div>';
		html +=	'</div>';
		//清除结构
		$('#search-goods .each').remove();
		//构造数据
		for(var key in data)
		{
			$obj = $(html);
			$obj.find('img').attr('src', data[key].taobao_info.image);
			$obj.find('.number').text(data[key].main_number);
			for(var k in data[key].sub_goods)
			{
				$('<a scode="' + data[key].sub_goods[k].search_code + '" sub-goods-number="' + data[key].sub_goods[k].number + '" sub-goods-id="' + data[key].sub_goods[k].sub_goods_id + '" class="color">' + data[key].sub_goods[k].attribute + '</a>').appendTo($obj.find('.colors'));
			}
			$obj.insertBefore('#search-goods .result .clear');
		}
		//绑定添加列表函数
		$('#search-goods .each a').click(function(){stock.add_to_list($(this));});
		$('#search-goods .result').show();
	},

	add_to_list : function($obj)
	{
		//先检查现有项目是否有问题
		if (!this.check_item())
		{
			//中断添加
			return;
		}
		//排除重复添加
		$each = $('.stock-create-list .each .goods-id');
		sub_goods_id = $obj.attr('sub-goods-id');
		/***
		for(var i=0; i<$each.length; i++)
		{
			if (sub_goods_id == $each.eq(i).val())
			{
				tool.customAlert({'obj':'请不要重复添加'});
				return;
			}
		}
		***/
		//初始化DOM
		var html = '';
		html +=	'<div class="each">';
		html +=	'<input type="hidden" class="goods-id" name="sub_goods_ids[]" value="" />';
		html +=	'<div class="goods-number"></div>';
		html +=	'<div class="goods-scode"></div>';
		html +=	'<div class="goods-attr"></div>';
		html +=	'<div class="goods-quantity"><input type="text" name="quantities[]" value="" /></div>';
		html +=	'<div class="goods-supplier"><select name="supplier_ids[]"></select></div>';
		html +=	'<div class="goods-price"><input type="text" name="prices[]" value="" /></div>';
		html +=	'<div class="store"><select name="store[]"><option value="1">主仓</option><option value="2">副仓</option></select></div>';
		html += '<div class="goods-transfer"><select name="from_store[]"><option value="1">主仓</option><option value="2">副仓</option></select></div>';
		html += '<div class="goods-transfer"><select name="to_store[]"><option value="1">主仓</option><option value="2" selected="selected">副仓</option></select></div>'
		html +=	'</div>';
		//获得供应商
		url = site.url + '/stock/ajax_get_suppliers/';
		data = tool.toJson('{"sub_goods_id":"' + $obj.attr('sub-goods-id') + '"}');
		style.loading('start');
		if ('object' == typeof stock.ajax)
		{
			stock.ajax.abort();
		}
		stock.ajax = $.post(url, data, function(result){
			//alert(result);
			j = tool.toJson(result);
			if ('ERROR' != j.r)
			{
				$dom = $(html);
				$dom.find('input.goods-id').val($obj.attr('sub-goods-id'));
				$dom.find('.goods-number').text($obj.attr('sub-goods-number'));
				$dom.find('.goods-scode').text($obj.attr('scode'));
				$dom.find('.goods-attr').text($obj.text());
				opts = '';
				for(var key in j.d)
				{
					opts += '<option value="' + j.d[key].supplier_id + '">' + j.d[key].detail.supplier_name + '</option>';
				}
				$dom.find('.goods-supplier select').append($(opts));
				//清除不必要的列
				stock.clear_col($dom, stock.type);
				$dom.appendTo('.stock-create-list .list');
				$('#finish').unbind('click').bind('click', function(){stock.submit()})
				//添加删除条目方法
				stock.remove_item();
				//添加检查重复项目方法
				stock.check_item();
				//添加触发检查项目的方法;
				stock.check_trigger();
				//处理仓位不能一样的方法
				stock.change_other_store();
			}
			else
			{
				tool.customAlert({'obj':j.d});
			}
			style.loading('end');
		})
	},

	//移除项目的方法
	remove_item : function()
	{
		var $items = $('.stock-create-list .each');
		var html = '';
		//解除事件绑定
		$items.unbind('mouseenter').unbind('mouseleave');

		//格式化
		html += '<div id="remove-item" style="width:25px;height:25px;line-height:25px;font-size:12px;text-align:center;float:right;cursor:pointer">删</div>';
		$items.bind('mouseenter', function(){
			$(html).appendTo($(this));
			$('#remove-item').click(function(){
				$(this).parent('.each').remove();
				stock.check_item();
			})
		})
		.bind('mouseleave', function(){
			$('#remove-item').remove();
		});
	},

	//处理调货时的仓位问题
	change_other_store : function()
	{
		if ('transfer' == stock.type)
		{
			$('.goods-transfer select').unbind('change')
			.bind('change', function(){
				var $this = $(this);
				var $other = $this.parent().siblings('.goods-transfer').find('select')
				if ($this.val() == $other.val())
				{
					$option = $other.find('option:selected');
					$other.children().removeAttr('selected');
					if ($option.next().length > 0)
					{
						$option.next().attr('selected', 'selected');
					}
					else if ($option.prev().length > 0)
					{
						$option.prev().attr('selected', 'selected');
					}
					else
					{
						$this.parents('.each').remove();
						tool.customAlert({'obj':'表单出错，请重新添加！'});
					}
				}
				//添加检查项目方法
				stock.check_item();
			})
		}
	},

	//检查重复项目的方法
	check_item : function()
	{
		var $items = $('.stock-create-list .each');
		var vars = [];
		for (i=0; i<$items.length; i++)
		{	
			var $item = $items.eq(i);
			var key = ''+$item.find('.goods-id').val()+$item.find('select[name="supplier_ids[]"]').val()+$item.find('select[name="store[]"]').val()+$item.find('input[name="prices[]"]').val()+$item.find('select[name="from_store[]"]').val()+$item.find('select[name="to_store[]"]').val();
			console.log(key);
			if (vars[key])
			{
				tool.customAlert({'obj':'存在待处理的重复项目。ID：'+$item.find('.goods-number').text()});
				$item.find('.goods-number').css({'background':'red','color':'white'});
				$('#finish').attr('id', 'unfinish')
				.unbind('click')
				.bind('click', function(){
					tool.customAlert({'obj':'存在待处理的项目！'});
				});
				return false;
			}
			else
			{
				vars[key] = true;
			}
		}
		if ($items.length > 0)
		{
			$items.find('.goods-number').removeAttr('style');
		}
		$('#unfinish').attr('id', 'finish')
		.unbind('click')
		.bind('click', function(){stock.submit()});
		return true;
	},

	//触发检查项目的动作
	check_trigger : function()
	{
		var $items = $('.stock-create-list .each');
		//输入框变动
		$items.find('input').unbind('blur')
		.bind('blur', function(){
			stock.check_item();
		});
		//选择器变动
		$items.find('select').unbind('change')
		.bind('change', function(){
			stock.check_item();
		});
	},

	submit : function(){
		$each = $('.stock-create-list .each');
		//是否添加货物
		if ($each.length > 0)
		{
			//判断是否数量为零
			//如果有价格则判断价格是否为数字
			for(var i=0; i<$each.length; i++)
			{
				if ($each.eq(i).find('.goods-quantity input').val() < 1)
				{
					tool.customAlert({'obj':'请添加数量'});
					return false;
				}
				if ($each.eq(i).find('.goods-price input').length > 0)
				{
					var price = $each.eq(i).find('.goods-price input').val();
					reg = new RegExp('^[0-9]+$');
					if (!reg.exec(price))
					{
						tool.customAlert({'obj':'价格必须是数字'});
						return false;
					}
				}
			}
		}
		else
		{
			tool.customAlert({'obj':'请添加货物'});
			return false;
		}
		//全部验证通过，组织JSON数据
		json = tool.formToJson($('input[name="quantities[]"]'), 'quantities', true);
		json += ',' + tool.formToJson($('input[name="sub_goods_ids[]"]'), 'sub_goods_ids', true);
		if ('S' == stock.type)
		{
			json += ',' + tool.formToJson($('select[name="store[]"]'), 'store', true);
			json += ',' + tool.formToJson($('select[name="supplier_ids[]"]'), 'supplier_ids', true);
			json += ',"bound_type_id":"' + $('input[name="bound_type_id"]').val() + '"';
		}
		else if ('S_P' == stock.type)
		{
			json += ',' + tool.formToJson($('select[name="store[]"]'), 'store', true);
			json += ',' + tool.formToJson($('select[name="supplier_ids[]"]'), 'supplier_ids', true);
			json += ',' + tool.formToJson($('input[name="prices[]"]'), 'prices', true);
			json += ',"bound_type_id":"' + $('input[name="bound_type_id"]').val() + '"';
		}
		else if ('N' == stock.type)
		{
			json += ',' + tool.formToJson($('select[name="store[]"]'), 'store', true);
			json += ',"bound_type_id":"' + $('input[name="bound_type_id"]').val() + '"';
		}
		else if ('transfer' == stock.type)
		{
			json += ',' + tool.formToJson($('select[name="from_store[]"]'), 'from_store', true);
			json += ',' + tool.formToJson($('select[name="to_store[]"]'), 'to_store', true);
		}
		json += ',"stock_type":"' + $('input[name=stock_type]').val() + '",';
		json += '"stock_bound_type":"' + $('input[name=stock_bound_type]').val() + '",';
		json += '"description":"' + $('input[name=description]').val() + '",';
		json += '"stock_date":"' + $('input[name=stock_date]').val() + '",';
		json += '"submit":"true"';
		json = '{' + json + '}';
		json = tool.toJson(json);
		console.log(json);
		//Do the ajax
		url = site.url + 'stock/create/';
		data = json;
		tool.customAlert({'obj':'提交中...请等候...'});
		style.loading('start');
		$.post(url, data, function(j){
			j = tool.toJson(j);
			if ('DONE' == j.r)
			{
				$('.stock-create-list .each').remove();
			}
			tool.customAlert({'obj':j.d});
			style.loading('end');
		});
	}

}